import { defineStore } from 'pinia'
import { io, Socket } from 'socket.io-client'

interface Message {
  id: string
  senderId: string
  senderName: string
  content: string
  timestamp: string
  type: 'text' | 'image' | 'file'
  fileUrl?: string
}

interface ChatRoom {
  id: string
  name: string
  type: 'course' | 'group' | 'private'
  participants: string[]
  lastMessage?: Message
  unreadCount: number
}

export const useChatStore = defineStore('chat', {
  state: () => ({
    socket: null as Socket | null,
    connected: false,
    currentRoom: null as ChatRoom | null,
    rooms: [] as ChatRoom[],
    messages: [] as Message[],
    loading: false,
    error: null as string | null
  }),

  actions: {
    initializeSocket() {
      if (this.socket) return

      this.socket = io('/chat', {
        path: '/api/socket.io',
        transports: ['websocket']
      })

      this.socket.on('connect', () => {
        this.connected = true
      })

      this.socket.on('disconnect', () => {
        this.connected = false
      })

      this.socket.on('message', (message: Message) => {
        this.addMessage(message)
      })

      this.socket.on('roomUpdate', (room: ChatRoom) => {
        this.updateRoom(room)
      })
    },

    async joinRoom(roomId: string) {
      try {
        this.loading = true
        if (!this.socket?.connected) {
          throw new Error('WebSocket未连接')
        }

        this.socket.emit('joinRoom', roomId)
        const response = await fetch(`/api/chat/rooms/${roomId}`)
        const roomData = await response.json()
        
        this.currentRoom = roomData
        await this.loadMessages(roomId)
      } catch (error) {
        this.error = '加入聊天室失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    async loadMessages(roomId: string) {
      try {
        const response = await fetch(`/api/chat/rooms/${roomId}/messages`)
        const messages = await response.json()
        this.messages = messages
      } catch (error) {
        this.error = '加载消息失败'
        throw error
      }
    },

    async sendMessage(content: string, type: 'text' | 'image' | 'file' = 'text', fileUrl?: string) {
      try {
        if (!this.currentRoom || !this.socket?.connected) {
          throw new Error('未加入聊天室或WebSocket未连接')
        }

        const message = {
          roomId: this.currentRoom.id,
          content,
          type,
          fileUrl
        }

        this.socket.emit('message', message)
      } catch (error) {
        this.error = '发送消息失败'
        throw error
      }
    },

    async loadRooms() {
      try {
        const response = await fetch('/api/chat/rooms')
        const rooms = await response.json()
        this.rooms = rooms
      } catch (error) {
        this.error = '加载聊天室列表失败'
        throw error
      }
    },

    addMessage(message: Message) {
      this.messages.push(message)
      if (this.currentRoom) {
        this.updateRoom({
          ...this.currentRoom,
          lastMessage: message
        })
      }
    },

    updateRoom(updatedRoom: ChatRoom) {
      const index = this.rooms.findIndex(room => room.id === updatedRoom.id)
      if (index !== -1) {
        this.rooms[index] = updatedRoom
      } else {
        this.rooms.push(updatedRoom)
      }

      if (this.currentRoom?.id === updatedRoom.id) {
        this.currentRoom = updatedRoom
      }
    },

    disconnect() {
      if (this.socket) {
        this.socket.disconnect()
        this.socket = null
        this.connected = false
        this.currentRoom = null
        this.messages = []
      }
    }
  }
})